package pathways;

/**
 * Title:        Pathways
 * Description:  Pure Java version of the Pathways Project.
 * Copyright:    Copyright (c) 2002
 * Company:      Ants Technologies
 * @author Veejay Sani
 * @version 1.0
 */

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import pathways.Database.Implementation.CDatabase;
import pathways.Database.Specialized.Visual.CSearchCompound;
import pathways.util.Debug.CDebug;
import ftp.FtpBean;

public class CUploadFile
{
  private CDatabase db;
  private JFrame owner;

  public CUploadFile(CDatabase database, JFrame owner)
  {
    db = database;
    this.owner = owner;
  }
    
  public void doUpload()
  {
    CCompound cmpd = searchCompound();
        
    if (cmpd != null)
    {
      JFileChooser chooser = new JFileChooser();
      chooser.setFileFilter(new CFileFilter());
      int returnVal = chooser.showOpenDialog(owner);
      if(returnVal == JFileChooser.APPROVE_OPTION) 
      {
        try {
          File f = chooser.getSelectedFile();
          String file = f.toString();
          file = file.replace('\\','/');
          String outFile = new String(cmpd.getID() + ".mol");
          
          transfer(file,outFile);
          
          JOptionPane.showMessageDialog(owner,"Transfer of file successful.","Success",JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception e) {
          CDebug.println(this,"doUpload() -- Unable to transfer file. Exception: " + e.toString());
          JOptionPane.showMessageDialog(owner,"Unable to transfer file.","Error",JOptionPane.ERROR_MESSAGE);
        }        
      }
    }    
  }
  
  private CCompound searchCompound()
  {
    CSearchCompound c = new CSearchCompound(true,owner.getFrames()[0],db,CSearchCompound.FILTER_NONE);
    
    c.show();
    
    return c.getSelectedCompound();
  }
  
  private boolean transfer(/*InputStream input, OutputStream output*/ String localFile, String remotFile)
  {
    /*int in = 0;
    try{
      while((in = input.read()) >= 0)
      {
        output.write(in);
      } 
    } catch(IOException ioe) {
      CDebug.println(this,"transfer() IOException: " + ioe.toString());
    }*/
    
    FtpBean ftp = new FtpBean();
    
    try{
       ftp.ftpConnect("freespace.dynu.com","Administrator","raja9124");
       ftp.setPassiveModeTransfer(false);
       ftp.putBinaryFile(localFile,remotFile);
       ftp.close();
       return true;
    } catch (Exception ex) {
       System.out.println(ex.toString());
       return false;
    }   
  }
}

class CFileFilter extends javax.swing.filechooser.FileFilter
{
  public boolean accept(File file)
  {
    if (file.isDirectory())
       return true;
       
    return file.getName().endsWith(".mol");      
  } 
  
  public String getDescription()
  {
    return "mol files (*.mol)"; 
  }
}